package com.accountant.travelaccountant;

import java.math.BigInteger;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Gravity;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class EditPurpose2 extends Activity {

	EditPurpose2 editPurpose2;
	TextView textViewForEditPurpose2;
	GridView gridViewForEditPurpose2;
	ListView listViewForEditPurpose2;
	EditPurpose2_GridViewAdapter editPurpose2_GridViewAdapter;
	EditPurpose2_ListViewAdapter editPurpose2_ListViewAdapter;
	private String memberName;
	DatabaseOperations_NonActivity databaseOperations;
	EditText input, input2;
	/* Alert Dialog */
	AlertDialog.Builder dialogBuilder, dialogBuilder2;
	AlertDialog alertDialog, alertDialog2;
	Intent intent;
	Bundle bundle;

	/* Variables for purpose and amount */
	String purpose = new String();
	BigInteger newPurposeAmount;

	/***********************************/
	/* Size for the account */
	BigInteger accountTotalSize;
	/* The amount table for amount */
	BigInteger amountTableAmount;
	/* Average for the above amount */
	BigInteger averageOfAmount;
	/* Get all the members in an arraylist */
	ArrayList<String> purposeList, memberList1, amountList;
	/* Get all the amounts paid by every member */
	ArrayList<String> memberAmounts;

	/***********************************/

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_purpose2);
		editPurpose2 = this;

		EditPurpose2_ListViewAdapter.setPurpose(null);
		/*
		 * Getting the member name
		 */
		intent = getIntent();
		bundle = intent.getExtras();
		memberName = bundle.getString("member");

		/* Getting the grid view adapter */
		gridViewForEditPurpose2 = (GridView) findViewById(R.id.gridViewForEditPurpose2);
		editPurpose2_GridViewAdapter = new EditPurpose2_GridViewAdapter(
				editPurpose2);
		gridViewForEditPurpose2.setAdapter(editPurpose2_GridViewAdapter);
		HelperClassForActivities.addColourToGridView(gridViewForEditPurpose2,
				this);

		/* Getting the listview adapter */
		listViewForEditPurpose2 = (ListView) findViewById(R.id.listViewforEditPurpose2);
		purposeList = new ArrayList<String>();
		amountList = new ArrayList<String>();
		editPurpose2_ListViewAdapter = new EditPurpose2_ListViewAdapter(
				editPurpose2, purposeList, amountList);
		listViewForEditPurpose2.setAdapter(editPurpose2_ListViewAdapter);
		/* Initializing the textbox at the top */
		textViewForEditPurpose2 = (TextView) findViewById(R.id.textViewforEditPurpose2);
		textViewForEditPurpose2.setText(memberName + "\'s expenses in "
				+ SessionClass_NonActivity.sessionObject().getTitle());
		textViewForEditPurpose2.setGravity(Gravity.CENTER);

		/* Creating an object of DatabaseOperations */
		databaseOperations = new DatabaseOperations_NonActivity(this);

		/* Opening the database */
		databaseOperations.openWriteableDatabase();

		/*
		 * Retrieving all the purposes for the first member of the array list of
		 * members so that at least the spinner is initialised. Later on we will
		 * do on event
		 */
		purposeList = databaseOperations.retrieveAll(
				DatabaseOperations_NonActivity.getPurposetable(),
				new String[] { DatabaseOperations_NonActivity
						.getPurposetablepurpose() },
				DatabaseOperations_NonActivity.getPurposetabletitle()
						+ "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle()
						+ "\" and "
						+ DatabaseOperations_NonActivity
								.getPurposetablepayingmember() + "=\""
						+ memberName + "\"", null, null, null, null);

		editPurpose2_ListViewAdapter = new EditPurpose2_ListViewAdapter(
				editPurpose2, purposeList, getPurposeAmounts(purposeList));
		listViewForEditPurpose2.setAdapter(editPurpose2_ListViewAdapter);

		/*
		 * Incase there are no purposes then it should not open at all and give
		 * a message that no purposes
		 */
		if (EditPurpose2_ListViewAdapter.getPurpose() != null) {

			/*
			 * Retrieving the amount for the very first purpose just to
			 * initialize
			 */
			@SuppressWarnings("unused")
			String amount = databaseOperations.retrieve(
					DatabaseOperations_NonActivity.getPurposetable(),
					new String[] { DatabaseOperations_NonActivity
							.getPurposetableamount() },
					DatabaseOperations_NonActivity.getPurposetabletitle()
							+ "=\""
							+ SessionClass_NonActivity.sessionObject()
									.getTitle()
							+ "\" and "
							+ DatabaseOperations_NonActivity
									.getPurposetablepayingmember()
							+ "=\""
							+ memberName
							+ "\" and "
							+ DatabaseOperations_NonActivity
									.getPurposetablepurpose() + "=\""
							+ EditPurpose2_ListViewAdapter.getPurpose() + "\"",
					null, null, null, null);
		} else {
		}
		/* Closing the database */
		databaseOperations.closeDatabase();

		/* Check if there is any purpose or not ese just destack this screen */
		if (purposeList.size() == 0) {
			Toast.makeText(getApplicationContext(),
					memberName + " hasn't spent anything", Toast.LENGTH_SHORT)
					.show();
			finish();
		}

	}

	/* Dialog box for editing a purpose amount */
	private void showDialogBoxEditPurposeAmount(String title, String message) {
		/* Creating the second dialog box */
		/* Firstly we create an object of AlertDialog.Builder */
		dialogBuilder2 = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder2.setTitle(title);
		dialogBuilder2.setMessage(message);
		/* Creating a textbox */
		input2 = new EditText(this);

		/* Setting the input type for this text box */
		input2.setInputType(InputType.TYPE_CLASS_NUMBER);

		/* Refill the textbox */
		input2.setSingleLine();

		/* Creating object to access its methods */
		databaseOperations = new DatabaseOperations_NonActivity(
				getApplicationContext());

		/* Opening the database */
		databaseOperations.openWriteableDatabase();

		input2.setText(databaseOperations.retrieve(
				DatabaseOperations_NonActivity.getPurposetable(),
				new String[] { DatabaseOperations_NonActivity
						.getPurposetableamount() },
				DatabaseOperations_NonActivity.getPurposetabletitle()
						+ "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle()
						+ "\" and "
						+ DatabaseOperations_NonActivity
								.getPurposetablepayingmember()
						+ "=\""
						+ memberName
						+ "\" and "
						+ DatabaseOperations_NonActivity
								.getPurposetablepurpose() + "=\""
						+ EditPurpose2_ListViewAdapter.getPurpose() + "\"",
				null, null, null, null));

		/* Fucntion to put the cursor at the last */
		Utils_NotActivity.setCursorPosition(input2);

		/* Close the database */
		databaseOperations.closeDatabase();

		dialogBuilder2.setView(input2);

		input2.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				Utils_NotActivity.validateNumberTextLength(input2);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		dialogBuilder2.setPositiveButton("Change",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						/*
						 * Suppose nothing entered in to the text box and
						 * whatever was there was deleted then it means nothing
						 * i.e 0
						 */
						if (input2.getText().length() == 0)
							newPurposeAmount = new BigInteger("0");
						else
							/* Getting the amount */
							newPurposeAmount = new BigInteger(input2.getText()
									.toString());
						/*
						 * If the amount is invalid say negative then do not
						 * accept it
						 */
						if (newPurposeAmount.intValue() < 0) {
							Toast.makeText(getApplicationContext(),
									"The amount entered is invalid",
									Toast.LENGTH_SHORT).show();
							return;
						}

						/* Opening the database */
						databaseOperations.openWriteableDatabase();

						/*
						 * Getting the purpose amount from the purpose table for
						 * that record you are trying to delete
						 */
						BigInteger oldPurposeAmount = new BigInteger(
								databaseOperations.retrieve(
										DatabaseOperations_NonActivity
												.getPurposetable(),
										new String[] { DatabaseOperations_NonActivity
												.getPurposetableamount() },
										DatabaseOperations_NonActivity
												.getPurposetabletitle()
												+ "=\""
												+ SessionClass_NonActivity
														.sessionObject()
														.getTitle()
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getPurposetablepayingmember()
												+ "=\""
												+ memberName
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getPurposetablepurpose()
												+ "=\""
												+ EditPurpose2_ListViewAdapter
														.getPurpose() + "\"",
										null, null, null, null));

						/* Getting the total amount for that title */
						BigInteger oldMemberAmount = new BigInteger(
								databaseOperations.retrieve(
										DatabaseOperations_NonActivity
												.getMembertable(),
										new String[] { DatabaseOperations_NonActivity
												.getMembertableamount() },
										DatabaseOperations_NonActivity
												.getMembertabletitle()
												+ "=\""
												+ SessionClass_NonActivity
														.sessionObject()
														.getTitle()
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getMembertablemember()
												+ "=\"" + memberName + "\"",
										null, null, null, null));

						/* Getting the total amount for that title */
						BigInteger oldTotalAmount = new BigInteger(
								databaseOperations.retrieve(
										DatabaseOperations_NonActivity
												.getAmounttable(),
										new String[] { DatabaseOperations_NonActivity
												.getAmounttableamount() },
										DatabaseOperations_NonActivity
												.getAmounttabletitle()
												+ "=\""
												+ SessionClass_NonActivity
														.sessionObject()
														.getTitle() + "\"",
										null, null, null, null));

						if (newPurposeAmount.intValue() < oldPurposeAmount
								.intValue()) {
							if (oldMemberAmount.intValue()
									- (oldPurposeAmount.intValue() - newPurposeAmount
											.intValue()) < 0
									|| oldTotalAmount.intValue()
											- (oldPurposeAmount.intValue() - newPurposeAmount
													.intValue()) < 0) {
								Toast.makeText(getApplicationContext(),
										"Amount Entered must be invalid",
										Toast.LENGTH_SHORT).show();
								return;
							} else {
								/* Update the purpose table purposes and amounts */
								databaseOperations.updateMoreThanOneColumn(
										DatabaseOperations_NonActivity
												.getPurposetable(),
										new String[] {
												DatabaseOperations_NonActivity
														.getPurposetablepurpose(),
												DatabaseOperations_NonActivity
														.getPurposetableamount() },
										new String[] {
												purpose,
												String.valueOf(newPurposeAmount
														.intValue()) },
										DatabaseOperations_NonActivity
												.getPurposetabletitle()
												+ "=\""
												+ SessionClass_NonActivity
														.sessionObject()
														.getTitle()
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getPurposetablepayingmember()
												+ "=\""
												+ memberName
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getPurposetablepurpose()
												+ "=\""
												+ EditPurpose2_ListViewAdapter
														.getPurpose() + "\"",
										null);

								/*
								 * Updating the amount in the member table
								 * because a purpose has been deleted
								 */
								databaseOperations.updateRow(
										DatabaseOperations_NonActivity
												.getMembertable(),
										DatabaseOperations_NonActivity
												.getMembertableamount(),
										String.valueOf(oldMemberAmount
												.intValue()
												- (oldPurposeAmount.intValue() - newPurposeAmount
														.intValue())),
										DatabaseOperations_NonActivity
												.getMembertabletitle()
												+ "=\""
												+ SessionClass_NonActivity
														.sessionObject()
														.getTitle()
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getMembertablemember()
												+ "=\"" + memberName + "\"",
										null);

								/*
								 * Updating the amount in the amount table
								 * because a purpose has been deleted
								 */
								databaseOperations.updateRow(
										DatabaseOperations_NonActivity
												.getAmounttable(),
										DatabaseOperations_NonActivity
												.getAmounttableamount(),
										String.valueOf(oldTotalAmount
												.intValue()
												- (oldPurposeAmount.intValue() - newPurposeAmount
														.intValue())),
										DatabaseOperations_NonActivity
												.getAmounttabletitle()
												+ "=\""
												+ SessionClass_NonActivity
														.sessionObject()
														.getTitle() + "\" ",
										null);

							}
						} else {
							/* Update the purpose table purposes and amounts */
							databaseOperations.updateMoreThanOneColumn(
									DatabaseOperations_NonActivity
											.getPurposetable(),
									new String[] {
											DatabaseOperations_NonActivity
													.getPurposetablepurpose(),
											DatabaseOperations_NonActivity
													.getPurposetableamount() },
									new String[] {
											purpose,
											String.valueOf(newPurposeAmount
													.intValue()) },
									DatabaseOperations_NonActivity
											.getPurposetabletitle()
											+ "=\""
											+ SessionClass_NonActivity
													.sessionObject().getTitle()
											+ "\" and "
											+ DatabaseOperations_NonActivity
													.getPurposetablepayingmember()
											+ "=\""
											+ memberName
											+ "\" and "
											+ DatabaseOperations_NonActivity
													.getPurposetablepurpose()
											+ "=\""
											+ EditPurpose2_ListViewAdapter
													.getPurpose() + "\"", null);

							/*
							 * Updating the amount in the member table because a
							 * purpose has been deleted
							 */
							databaseOperations.updateRow(
									DatabaseOperations_NonActivity
											.getMembertable(),
									DatabaseOperations_NonActivity
											.getMembertableamount(),
									String.valueOf(oldMemberAmount.intValue()
											+ newPurposeAmount.intValue()
											- oldPurposeAmount.intValue()),
									DatabaseOperations_NonActivity
											.getMembertabletitle()
											+ "=\""
											+ SessionClass_NonActivity
													.sessionObject().getTitle()
											+ "\" and "
											+ DatabaseOperations_NonActivity
													.getMembertablemember()
											+ "=\"" + memberName + "\"", null);

							/*
							 * Updating the amount in the amount table because a
							 * purpose has been deleted
							 */
							databaseOperations.updateRow(
									DatabaseOperations_NonActivity
											.getAmounttable(),
									DatabaseOperations_NonActivity
											.getAmounttableamount(),
									String.valueOf(oldTotalAmount.intValue()
											+ newPurposeAmount.intValue()
											- oldPurposeAmount.intValue()),
									DatabaseOperations_NonActivity
											.getAmounttabletitle()
											+ "=\""
											+ SessionClass_NonActivity
													.sessionObject().getTitle()
											+ "\" ", null);
						}

						/*
						 * Getting the list of all purposes and assigning to the
						 * spinner because after deleting the member we need to
						 * update
						 */
						purposeList = databaseOperations.retrieveAll(
								DatabaseOperations_NonActivity
										.getPurposetable(),
								new String[] { DatabaseOperations_NonActivity
										.getPurposetablepurpose() },
								DatabaseOperations_NonActivity
										.getPurposetabletitle()
										+ "=\""
										+ SessionClass_NonActivity
												.sessionObject().getTitle()
										+ "\" and "
										+ DatabaseOperations_NonActivity
												.getPurposetablepayingmember()
										+ "=\"" + memberName + "\"", null,
								null, null, null);
						// adapter = new ArrayAdapter<String>(
						// getApplicationContext(),
						// android.R.layout.simple_spinner_item,
						// purposeList);
						// spnPurposes.setAdapter(adapter);
						editPurpose2_ListViewAdapter = new EditPurpose2_ListViewAdapter(
								editPurpose2, purposeList,
								getPurposeAmounts(purposeList));
						listViewForEditPurpose2
								.setAdapter(editPurpose2_ListViewAdapter);

						/*
						 * Updating the member table by calling the function of
						 * purpose class
						 */
						updateToGetAndToGiveColumns();

						/* Code to close the database */
						databaseOperations.closeDatabase();
						EditPurpose2_ListViewAdapter.setPurpose(null);
					}
				});

		dialogBuilder2.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						return;
					}
				});

		alertDialog2 = dialogBuilder2.create();
		alertDialog2.show();
	}

	/* Dialog box for editing a purpose */
	private void showDialogBoxEditPurpose(String title, String message) {

		/* Creating object to access its methods */
		databaseOperations = new DatabaseOperations_NonActivity(
				getApplicationContext());

		/* Opening the database */
		databaseOperations.openWriteableDatabase();

		/* Firstly we create an object of AlertDialog.Builder */
		dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);

		/* Creating a textbox */
		input = new EditText(this);
		input.setSingleLine();
		/* The purpose should be already there whatever is selected */
		input.setText(databaseOperations.retrieve(
				DatabaseOperations_NonActivity.getPurposetable(),
				new String[] { DatabaseOperations_NonActivity
						.getPurposetablepurpose() },
				DatabaseOperations_NonActivity.getPurposetabletitle()
						+ "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle()
						+ "\" and "
						+ DatabaseOperations_NonActivity
								.getPurposetablepayingmember()
						+ "=\""
						+ memberName
						+ "\" and "
						+ DatabaseOperations_NonActivity
								.getPurposetablepurpose() + "=\""
						+ EditPurpose2_ListViewAdapter.getPurpose() + "\"",
				null, null, null, null));

		/* Function to put the cursor at the last */
		Utils_NotActivity.setCursorPosition(input);

		/* Getting the purpose */
		purpose = input.getText().toString();

		/* Close the database */
		databaseOperations.closeDatabase();

		/* Assigning that text field to dialogBuilder */
		dialogBuilder.setView(input);

		input.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				Utils_NotActivity.validateTextLength(input);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		dialogBuilder.setPositiveButton("Change",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						if (input.getText().toString().replaceAll("\\s+", " ")
								.trim().length() != 0) {
							/* Opening the database */
							databaseOperations.openWriteableDatabase();
							/* Getting the purpose */
							purpose = input.getText().toString()
									.replaceAll("\\s+", " ").trim();

							/* Closing the database */
							databaseOperations.closeDatabase();

							showDialogBoxEditPurposeAmount("Edit this amount",
									"Enter the new amount");

						} else {
							Toast.makeText(getApplicationContext(),
									"Purpose cannot be blank",
									Toast.LENGTH_SHORT).show();
							dialog.dismiss();
						}
					}
				});

		dialogBuilder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						return;
					}
				});

		alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	/* Dialog box for Deleting a purpose */
	private void showDialogBoxDeletePurpose(String title, String message) {

		/* Creating object to access its methods */
		databaseOperations = new DatabaseOperations_NonActivity(
				getApplicationContext());

		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);
		dialogBuilder.setPositiveButton("Yes",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						/* Code to open the database */
						databaseOperations.openWriteableDatabase();

						/*
						 * Getting the purpose amount from the purpose table for
						 * that record you are trying to delete
						 */
						BigInteger purposeAmount = new BigInteger(
								databaseOperations.retrieve(
										DatabaseOperations_NonActivity
												.getPurposetable(),
										new String[] { DatabaseOperations_NonActivity
												.getPurposetableamount() },
										DatabaseOperations_NonActivity
												.getPurposetabletitle()
												+ "=\""
												+ SessionClass_NonActivity
														.sessionObject()
														.getTitle()
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getPurposetablepayingmember()
												+ "=\""
												+ memberName
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getPurposetablepurpose()
												+ "=\""
												+ EditPurpose2_ListViewAdapter
														.getPurpose() + "\"",
										null, null, null, null));

						/* Getting the total amount for that title */
						BigInteger memberAmount = new BigInteger(
								databaseOperations.retrieve(
										DatabaseOperations_NonActivity
												.getMembertable(),
										new String[] { DatabaseOperations_NonActivity
												.getMembertableamount() },
										DatabaseOperations_NonActivity
												.getMembertabletitle()
												+ "=\""
												+ SessionClass_NonActivity
														.sessionObject()
														.getTitle()
												+ "\" and "
												+ DatabaseOperations_NonActivity
														.getMembertablemember()
												+ "=\"" + memberName + "\"",
										null, null, null, null));

						/*
						 * Deleting the particular records by going to the
						 * title->member->purpose
						 */
						if (databaseOperations.deleteRow(
								DatabaseOperations_NonActivity
										.getPurposetable(),
								DatabaseOperations_NonActivity
										.getPurposetabletitle()
										+ "=\""
										+ SessionClass_NonActivity
												.sessionObject().getTitle()
										+ "\" and "
										+ DatabaseOperations_NonActivity
												.getPurposetablepayingmember()
										+ "=\""
										+ memberName
										+ "\" and "
										+ DatabaseOperations_NonActivity
												.getPurposetablepurpose()
										+ "=\""
										+ EditPurpose2_ListViewAdapter
												.getPurpose() + "\"", null) != 0) {

							/*
							 * Updating the amount in the member table because a
							 * purpose has been deleted
							 */
							databaseOperations.updateRow(
									DatabaseOperations_NonActivity
											.getMembertable(),
									DatabaseOperations_NonActivity
											.getMembertableamount(),
									String.valueOf(memberAmount.intValue()
											- purposeAmount.intValue()),
									DatabaseOperations_NonActivity
											.getMembertabletitle()
											+ "=\""
											+ SessionClass_NonActivity
													.sessionObject().getTitle()
											+ "\" and "
											+ DatabaseOperations_NonActivity
													.getMembertablemember()
											+ "=\"" + memberName + "\"", null);

							/* Updating the amount in the amount table */
							/* Getting the total amount for that title */
							BigInteger totalAmount = new BigInteger(
									databaseOperations.retrieve(
											DatabaseOperations_NonActivity
													.getAmounttable(),
											new String[] { DatabaseOperations_NonActivity
													.getAmounttableamount() },
											DatabaseOperations_NonActivity
													.getAmounttabletitle()
													+ "=\""
													+ SessionClass_NonActivity
															.sessionObject()
															.getTitle() + "\"",
											null, null, null, null));

							/*
							 * Updating the amount in the amount table because a
							 * purpose has been deleted
							 */
							databaseOperations.updateRow(
									DatabaseOperations_NonActivity
											.getAmounttable(),
									DatabaseOperations_NonActivity
											.getAmounttableamount(),
									String.valueOf(totalAmount.intValue()
											- purposeAmount.intValue()),
									DatabaseOperations_NonActivity
											.getAmounttabletitle()
											+ "=\""
											+ SessionClass_NonActivity
													.sessionObject().getTitle()
											+ "\" ", null);

							/*
							 * Getting the list of all purposes and assigning to
							 * the spinner because after deleting the member we
							 * need to update
							 */
							purposeList = databaseOperations.retrieveAll(
									DatabaseOperations_NonActivity
											.getPurposetable(),
									new String[] { DatabaseOperations_NonActivity
											.getPurposetablepurpose() },
									DatabaseOperations_NonActivity
											.getPurposetabletitle()
											+ "=\""
											+ SessionClass_NonActivity
													.sessionObject().getTitle()
											+ "\" and "
											+ DatabaseOperations_NonActivity
													.getPurposetablepayingmember()
											+ "=\"" + memberName + "\"", null,
									null, null, null);
							editPurpose2_ListViewAdapter = new EditPurpose2_ListViewAdapter(
									editPurpose2, purposeList,
									getPurposeAmounts(purposeList));
							listViewForEditPurpose2
									.setAdapter(editPurpose2_ListViewAdapter);

							/*
							 * Updating the member table by calling the function
							 * of purpose class
							 */
							updateToGetAndToGiveColumns();
							EditPurpose2_ListViewAdapter.setPurpose(null);
							/* Code to close the database */
							databaseOperations.closeDatabase();
							/*In case every thing has been deleted then we will go back to the previous screen*/
							if (purposeList.size() == 0) {
								finish();
							}
							return;
						}

					}
				});

		dialogBuilder.setNegativeButton("No",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						return;
					}
				});

		AlertDialog alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	/* After deleting a purpose again we need to update the member table */
	public void updateToGetAndToGiveColumns() {
		/* Retrieve the size of the Amount Table */
		accountTotalSize = new BigInteger(databaseOperations.retrieve(
				DatabaseOperations_NonActivity.getAmounttable(),
				new String[] { DatabaseOperations_NonActivity
						.getAmounttabletotalmembers() },
				DatabaseOperations_NonActivity.getAmounttabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle()
						+ "\"", null, null, null, null));

		/*
		 * Incase all the members have been deleted then this function should
		 * not be allowed to proceed further
		 */
		if (accountTotalSize.intValue() == 0)
			return;
		/* Retrieve the amount table amount */
		amountTableAmount = new BigInteger(databaseOperations.retrieve(
				DatabaseOperations_NonActivity.getAmounttable(),
				new String[] { DatabaseOperations_NonActivity
						.getAmounttableamount() },
				DatabaseOperations_NonActivity.getAmounttabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle()
						+ "\"", null, null, null, null));
		/* Calculating the average */
		averageOfAmount = amountTableAmount.divide(accountTotalSize);

		/* Retrieving all the members of the particular account */
		memberList1 = databaseOperations.retrieveAll(
				DatabaseOperations_NonActivity.getMembertable(),
				new String[] { DatabaseOperations_NonActivity
						.getMembertablemember() },
				DatabaseOperations_NonActivity.getMembertabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle()
						+ "\"", null, null, null, null);

		/* Retrieving all the amounts of the particular accounts */
		memberAmounts = databaseOperations.retrieveAll(
				DatabaseOperations_NonActivity.getMembertable(),
				new String[] { DatabaseOperations_NonActivity
						.getMembertableamount() },
				DatabaseOperations_NonActivity.getMembertabletitle() + "=\""
						+ SessionClass_NonActivity.sessionObject().getTitle()
						+ "\"", null, null, null, null);

		for (int i = 0; i < accountTotalSize.intValue(); i++) {
			/*
			 * Suppose a person has given more then he has to receive from his
			 * friends
			 */
			if ((new BigInteger(memberAmounts.get(i))).intValue() >= averageOfAmount
					.intValue()) {
				/* Updating the to get column */
				databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getMembertable(),
						DatabaseOperations_NonActivity.getMembertabletoget(),
						String.valueOf((new BigInteger(memberAmounts.get(i)))
								.intValue() - averageOfAmount.intValue()),
						DatabaseOperations_NonActivity.getMembertabletitle()
								+ "="
								+ "\""
								+ SessionClass_NonActivity.sessionObject()
										.getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity
										.getMembertablemember() + "=" + "\""
								+ memberList1.get(i) + "\"", null);

				/* Making the to give columns */
				databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getMembertable(),
						DatabaseOperations_NonActivity.getMembertabletogive(),
						String.valueOf(0),
						DatabaseOperations_NonActivity.getMembertabletitle()
								+ "="
								+ "\""
								+ SessionClass_NonActivity.sessionObject()
										.getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity
										.getMembertablemember() + "=" + "\""
								+ memberList1.get(i) + "\"", null);
			}
			/*
			 * Suppose a person has given less then he has to give to his
			 * friends
			 */
			else if ((new BigInteger(memberAmounts.get(i))).intValue() < averageOfAmount
					.intValue()) {
				/* Updating the to give column */
				databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getMembertable(),
						DatabaseOperations_NonActivity.getMembertabletogive(),
						String.valueOf(averageOfAmount.intValue()
								- (new BigInteger(memberAmounts.get(i)))
										.intValue()),
						DatabaseOperations_NonActivity.getMembertabletitle()
								+ "="
								+ "\""
								+ SessionClass_NonActivity.sessionObject()
										.getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity
										.getMembertablemember() + "=" + "\""
								+ memberList1.get(i) + "\"", null);

				databaseOperations.updateRow(
						DatabaseOperations_NonActivity.getMembertable(),
						DatabaseOperations_NonActivity.getMembertabletoget(),
						String.valueOf(0),
						DatabaseOperations_NonActivity.getMembertabletitle()
								+ "="
								+ "\""
								+ SessionClass_NonActivity.sessionObject()
										.getTitle()
								+ "\" and "
								+ DatabaseOperations_NonActivity
										.getMembertablemember() + "=" + "\""
								+ memberList1.get(i) + "\"", null);
			}
		}
	}

	public void edit() {
		/* Check for the account being selected or not */
		if (checkIfAnyAccountHasBeenSelectedOrNot()) {
			return;
		}
		/*
		 * Check for if the database does not exist go directly go to front
		 * screen
		 */
		if (Utils_NotActivity.databaseDoesNotExist(getApplicationContext())) {
			Intent intent1 = new Intent(EditPurpose2.this, FrontScreen.class);
			startActivity(intent1);
			return;
		}
		if (EditPurpose2_ListViewAdapter.getPurpose() == null) {
			Toast.makeText(getApplicationContext(), "No Purposes To Edit",
					Toast.LENGTH_SHORT).show();
			return;
		}
		showDialogBoxEditPurpose("Edit this purpose",
				"Change your purpoose here");
	}

	public void delete() {
		/* Check for the account being selected or not */
		if (checkIfAnyAccountHasBeenSelectedOrNot()) {
			return;
		}
		/*
		 * Check for if the database does not exist go directly go to front
		 * screen
		 */
		if (Utils_NotActivity.databaseDoesNotExist(getApplicationContext())) {
			Intent intent1 = new Intent(EditPurpose2.this, FrontScreen.class);
			startActivity(intent1);
			return;
		}
		/*
		 * Case where a member has no purposes at all then we should not allow
		 * to delete
		 */
		if (EditPurpose2_ListViewAdapter.getPurpose() == null) {
			Toast.makeText(getApplicationContext(), "No Purpose To Delete",
					Toast.LENGTH_SHORT).show();
			return;
		}

		showDialogBoxDeletePurpose("Delete Member", "Do you want to delete "
				+ EditPurpose2_ListViewAdapter.getPurpose());
	}

	/* A function to check whether the account was selected or not */
	private boolean checkIfAnyAccountHasBeenSelectedOrNot() {
		if (EditPurpose2_ListViewAdapter.getPurpose() == null) {
			Toast.makeText(getApplicationContext(), "No Account Selected",
					Toast.LENGTH_SHORT).show();
			return true;
		}
		return false;
	}

	private ArrayList<String> getPurposeAmounts(ArrayList<String> purposes) {
		ArrayList<String> amounts = new ArrayList<String>();
		for (int i = 0; i < purposes.size(); i++) {
			amounts.add(databaseOperations.retrieve(
					DatabaseOperations_NonActivity.getPurposetable(),
					new String[] { DatabaseOperations_NonActivity
							.getPurposetableamount() },
					DatabaseOperations_NonActivity.getPurposetabletitle()
							+ "=\""
							+ SessionClass_NonActivity.sessionObject()
									.getTitle()
							+ "\" and "
							+ DatabaseOperations_NonActivity
									.getPurposetablepayingmember()
							+ "=\""
							+ memberName
							+ "\" and "
							+ DatabaseOperations_NonActivity
									.getPurposetablepurpose() + "=\""
							+ purposes.get(i) + "\"", null, null, null, null));
		}
		return amounts;
	}

}
